package com.fla.puzzle.ui.support;

import android.content.Context;
import android.database.DataSetObserver;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

public class CustomGallery extends HorizontalScrollView {

    private BaseAdapter adapter;
    private OnItemClickListener onItemClickListener;

    public CustomGallery(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public CustomGallery(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomGallery(Context context) {
        super(context);
    }

    public void setAdapter(BaseAdapter adapter) {
        this.adapter = adapter;
        updateData();
        adapter.registerDataSetObserver(new DataSetChangedHandler());
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;

    }

    private void updateData() {
        removeAllViewsInLayout();

        LinearLayout container = new LinearLayout(getContext());
        addView(container);

        fillFromAdapter(container);
    }

    private void fillFromAdapter(LinearLayout container) {
        for (int i = 0; i < adapter.getCount(); i++) {
            final View view = adapter.getView(i, null, container);
            view.setOnClickListener(new OnItemClickHandler(i));
            container.addView(view);
        }
    }

    private class OnItemClickHandler implements OnClickListener {
        private final int position;

        public OnItemClickHandler(int position) {
            this.position = position;
        }

        @Override
        public void onClick(View view) {
            if (onItemClickListener != null) {
                onItemClickListener.onItemClick(null, view, position, adapter.getItemId(position));
            }
        }
    }

    private class DataSetChangedHandler extends DataSetObserver {
        @Override
        public void onChanged() {
            updateData();
        }

        @Override
        public void onInvalidated() {
            updateData();
        }
    }
}
